import MapApi from '@/api/MapApi';
import locationStore from '@/stores/LocationStore';
import { showToast } from '@tarojs/taro';
import { CommonUtil } from '@/utils/CommonUtil';
import MapConstant from '@/constant/MapConstant';
import useHouse from '@/hooks/useHouse';

export default class MapBusiness {
  static async getLocationName(latitude: number, longitude: number) {
    const {getMarketHouseList} = useHouse();
    const {setMinLat, setMaxLat, setMinLng, setMaxLng} = locationStore;
    try {
      const {setLongitude, setLatitude, setTitle, setAddress, setCategory} = locationStore;
      const res: any = await MapApi.getLocationName(latitude, longitude);
      if (res.result?.pois instanceof Array) {
        const {address, category, title, location} = res.result.pois[0];
        address && setAddress(address);
        category && setCategory(category);
        title && setTitle(title);
        location?.lat && setLatitude(location.lat);
        location?.lng && setLongitude(location.lng);
        const {
          minLat,
          minLng,
          maxLng,
          maxLat
        } = CommonUtil.calculateCoordinatesWithinRadius(location.lat, location.lng, MapConstant.HOUSE_MARK_RANGE);
        setMinLat(minLat);
        setMaxLat(maxLat);
        setMinLng(minLng);
        setMaxLng(maxLng);
        // 在已选位置的基础上进行获取房屋信息
        await getMarketHouseList(minLat, maxLat, minLng, maxLng);
      }
    } catch (e) {
      showToast({
        title: '获取位置失败！',
        icon: 'error'
      });
    }
  }
}